#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/7/4 17:30
# @Author : 闫峰
# @File    : price_syc.py
from datetime import datetime
from decimal import Decimal

import requests

from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database


class TestPriceSyc:

    def test_price_syc(self):
        """
        测试价格同步
        :param client:
        :return:
        """

        headers = {
            "Authorization": "Basic YXBpdXNlcjo3a3MwLXRfME9wUTFJcmE4NQ=="
        }
        maxId = None
        listing_list = []
        while True:
            if not maxId:
                data = {
                    "startTime": "2020-01-01 06:22:16",
                    "endTime": "2024-12-30 06:22:16"
                }
            else:
                data = {
                    "startTime": "2020-01-01 06:22:16",
                    "endTime": "2024-12-30 06:22:16",
                    "maxId": maxId
                }
            """
            url: https://gathercenterapi.zhcxkj.com
            username: apiuser
            password: 7ks0-t_0OpQ1Ira85
              # temu产品列表接口  
              temu-product-list:
                  get-url: /Temu/TemuResult/GetProductList
            """
            res = requests.post('https://gathercenterapi.zhcxkj.com/Temu/TemuResult/GetProductList', json=data,
                                headers=headers)
            if res.status_code == 200:
                res_json = res.json()
                data_list = res_json.get('data')
                if not data_list:
                    break
                maxId = data_list[-1].get('Id')
                listing_list.extend(data_list)
        # 取创建时间最新得一条数据
        # 使用字典来存储每个SKUID+SKCID组合的最新记录
        latest_records = {}

        # 遍历数据列表，更新字典中的记录
        for item in listing_list:
            key = (item["SKUID"], item["SKCID"])
            if key not in latest_records or datetime.strptime(item["__CreateDateTime"],
                                                              '%Y-%m-%d %H:%M:%S.%f') > datetime.strptime(
                latest_records[key]["__CreateDateTime"], '%Y-%m-%d %H:%M:%S.%f'):
                latest_records[key] = item

        # 如果你只想要一个列表而不是字典，可以这样做：
        latest_records_list = list(latest_records.values())
        insert_map_list = list(map(lambda x: list(x.values()), latest_records_list))

        def convert_fifth_to_int(sublist):
            # 假设子列表至少有五个元素
            sublist = sublist[:]  # 创建一个子列表的副本以避免修改原始列表

            sublist[5] = int(sublist[5])  # 将第五个元素转换为int
            sublist[6] = int(sublist[6])  # 将第五个元素转换为int
            sublist[7] = int(sublist[7])  # 将第五个元素转换为int
            sublist[9] = Decimal(sublist[9])  # 将第五个元素转换为int
            return sublist

        insert_map_list = list(map(convert_fifth_to_int, insert_map_list))
        db_java_test = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        insert_sql = """
        REPLACE INTO monitor.t_temu_listing_product 
        (api_id,crawl_config_id,login_user_name,create_datetime,source_name,pf_sku_id,pf_spu_id,pf_skc_id,article_number,declared_price,date_site,currency_type,user_id,site,account_type,listing_time,row_md5)
        VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
                        """
        rows = db_java_test.execute_many(insert_sql, insert_map_list)
        print(f"插入了{rows}条")


if __name__ == '__main__':
    TestPriceSyc().test_price_syc()
